package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Menu;
import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.RoleMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IRoleService;
import cn.wolfcode.crm.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {

    @Autowired
    RoleMapper mapper;

    @Override
    public int insert(Role record) {
        int count = mapper.insert(record);
        //权限
        List<Permission> permissions = record.getPermissions();
        //关联关系
        for (Permission permission : permissions) {
            mapper.insertPermissionRelation(record.getId(),permission.getId());
        }

        //菜单
        List<Menu> menus = record.getMenus();
        //关联关系
        for (Menu menu : menus) {
            mapper.insertMenuRelation(record.getId(),menu.getId());
        }

        return count ;
    }

    @Override
    public Role selectByPrimaryKey(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Role> selectAll() {
        return mapper.selectAll();
    }

    @Override
    public int updateByPrimaryKey(Role record) {

        //删除权限关系
        mapper.deletePermissionRelation(record.getId());

        List<Permission> permissions = record.getPermissions();
        //关联权限关系
        for (Permission permission : permissions) {
            mapper.insertPermissionRelation(record.getId(),permission.getId());
        }

        //删除菜单关系
        mapper.deleteMenuRelation(record.getId());
        //菜单
        List<Menu> menus = record.getMenus();
        //关联关系
        for (Menu menu : menus) {
            mapper.insertMenuRelation(record.getId(),menu.getId());
        }

        return mapper.updateByPrimaryKey(record);
    }

    @Override
    public PageResult query(QueryObject qo) {
        //查询总数
        int count = mapper.queryCount();
        //如果总数>1就查询结果集
        if(count>0){
           return new PageResult(count,mapper.queryList(qo));
        }
        return new PageResult(0, Collections.EMPTY_LIST);
    }

    @Override
    public List<Long> selectByEmployeeId(Long employeeId) {
        return mapper.selectByEmployeeId(employeeId);
    }

    @Override
    public List<String> selectNameByEmployeeId(Long employeeId) {
        return mapper.selectNameByEmployeeId(employeeId);
    }

}
